<template>
  <div class="product-detail-container">
    <el-card class="product-card">
      <div class="product-layout">
        <div class="product-image">
          <el-image :src="ruleForm.image" fit="cover" />
        </div>
        
        <div class="product-info">
          <h1 class="product-name">{{ ruleForm.productName }}</h1>
          
          <div class="price-section">
            <div class="price">¥{{ ruleForm.price }}</div>
            <div class="stock">库存: {{ ruleForm.stock }}件</div>
          </div>
          
          <div class="description-section">
            <h3>商品描述</h3>
            <p>{{ ruleForm.description }}</p>
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" size="large" @click="addgouwu">
              <el-icon><ShoppingCart /></el-icon>
              加入购物车
            </el-button>
            <el-button type="danger" size="large" @click="xiadan">
              <el-icon><Shop /></el-icon>
              立即购买
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 选择地址对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="选择收货地址"
      width="500px"
      custom-class="address-dialog"
    >
      <div class="address-form">
        <el-form label-position="top">
          <el-form-item label="选择省份">
            <el-select
              v-model="order.shengId"
              placeholder="请选择省份"
              class="address-select"
              @change="getShi"
            >
              <el-option
                v-for="item in sheng"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择城市">
            <el-select
              v-model="order.shiId"
              placeholder="请选择城市"
              class="address-select"
            >
              <el-option
                v-for="item in shi"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        
        <div class="order-summary">
          <div class="summary-item">
            <span>商品总价:</span>
            <span class="price">¥{{ order.totalmount }}</span>
          </div>
        </div>
        
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="xiadan2">
            确认下单
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 加入购物车成功提示 -->
    <el-dialog
      v-model="dialogVisible2"
      title="提示"
      width="300px"
      center
      custom-class="success-dialog"
    >
      <div class="success-message">
        <el-icon class="success-icon" color="#67C23A" :size="48"><CircleCheckFilled /></el-icon>
        <p>成功加入购物车！</p>
      </div>
      <div class="dialog-footer">
        <el-button @click="dialogVisible2 = false">继续购物</el-button>
        <el-button type="primary" @click="goToCart">
          去购物车结算
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { ref } from "vue";
import axios from "axios";
import { findSehng, findShi } from "@/assets/city.js";
import { xiadan22, createOrder } from "@/assets/list.js";
import { ShoppingCart, Shop, CircleCheckFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import {add} from "@/assets/cart.js";

const dialogVisible2 = ref(false)
const dialogVisible = ref(false)
const router = useRouter()
const aa = useRoute()
const id = aa.query.id

const order = ref({
  userId: localStorage.getItem("userId"),
  totalmount: "",
  productId: "",
  shengId: "",
  shiId: ""
})

const ruleForm = ref({
  id: "",
  productName: "",
  price: "",
  stock: "",
  description: ""
})

const sheng = ref([])
const shi = ref([])
const cartform=ref({
  userId:localStorage.getItem("userId"),
  productId:"",
  quantity:1
})
function addgouwu() {
  dialogVisible2.value = true
  cartform.value.productId=ruleForm.value.id
  add(cartform.value)
}

function goToCart() {
  dialogVisible2.value = false
  router.push('/cart')
}

function xiadan() {
  order.value.productId = ruleForm.value.id
  order.value.totalmount = ruleForm.value.price
  dialogVisible.value = true
}

function xiadan2() {
  if (!order.value.shengId || !order.value.shiId) {
    ElMessage.warning('请选择收货地址');
    return;
  }

  // 构建订单数据
  const orderData = {
    userId: parseInt(localStorage.getItem('userId')), // 确保userId是数字类型
    totalAmount: parseFloat(order.value.totalmount), // 确保金额是数字类型
    shengName: sheng.value.find(item => item.id === order.value.shengId)?.name || '',
    shiName: shi.value.find(item => item.id === order.value.shiId)?.name || '',
    orderStatus: 1, // 1: 待支付
    productId: parseInt(order.value.productId) // 确保productId是数字类型
  };

  // 打印请求数据以便调试
  console.log('提交的订单数据:', orderData);

  createOrder(orderData).then(res => {
    console.log('服务器响应:', res);
    if (res.code === 200) {
      dialogVisible.value = false;
      ElMessage.success('下单成功！');
      router.push('/geren'); // 跳转到个人中心
    } else {
      ElMessage.error(res.message || '下单失败');
    }
  }).catch(err => {
    console.error('下单失败:', err);
    ElMessage.error('下单失败，请稍后重试');
  });
}

function getShi() {
  findShi(order.value.shengId).then(res => {
    shi.value = res.data
  })
}

function getSheng() {
  findSehng().then(res => {
    sheng.value = res.data
  })
}

function show3() {
  axios({
    url: "/api/userad/us/list2",
    method: "post",
    params: { id: id },
  }).then((res) => {
    ruleForm.value = res.data.data
  })
}

getSheng()
show3()
</script>

<style scoped>
.product-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.product-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.product-layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  padding: 20px;
}

.product-image {
  width: 100%;
  height: 400px;
  overflow: hidden;
  border-radius: 8px;
}

.product-image :deep(.el-image) {
  width: 100%;
  height: 100%;
}

.product-info {
  padding: 20px;
}

.product-name {
  font-size: 24px;
  color: #303133;
  margin: 0 0 20px;
}

.price-section {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.price {
  font-size: 28px;
  color: #f56c6c;
  font-weight: bold;
}

.stock {
  margin-top: 10px;
  color: #67c23a;
}

.description-section {
  margin: 20px 0;
}

.description-section h3 {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.description-section p {
  color: #606266;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.action-buttons :deep(.el-button) {
  flex: 1;
  height: 48px;
}

.action-buttons :deep(.el-icon) {
  margin-right: 8px;
}

/* 对话框样式 */
:deep(.address-dialog) {
  border-radius: 8px;
}

.address-form {
  padding: 20px 0;
}

.address-select {
  width: 100%;
}

.order-summary {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-item .price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

/* 成功提示对话框 */
.success-dialog {
  text-align: center;
}

.success-message {
  padding: 20px 0;
}

.success-message p {
  margin-top: 15px;
  color: #67c23a;
  font-size: 16px;
}

@media (max-width: 768px) {
  .product-layout {
    grid-template-columns: 1fr;
  }
  
  .product-image {
    height: 300px;
  }
}
</style>
